<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">

      <el-input @keyup.enter.native="handleFilter" v-model="listQuery.name" style="width: 200px;" class="filter-item" placeholder="类别名称" clearable>
      </el-input>

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>

      <el-button v-if="sys_category_add" class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleDownload">导出</el-button>

    </div>

    <el-table :key='tableKey' id="mainte" :data="list" v-loading="listLoading" element-loading-text="给我一点时间" stripe border fit highlight-current-row style="width: 100%">

      <!-- <el-table-column align="center" label="ID">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="编码">
        <template slot-scope="scope">
          <span>
           {{scope.row.code}}
          </span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="修改时间">
        <template slot-scope="scope">
          <span>{{scope.row.updateTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="sys_category_upd" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="sys_category_del" size="small" type="danger" @click="deletes(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"></el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/facilityType/category'
import waves from '@/directive/waves/index.js' // 水波纹指令
import { mapGetters } from 'vuex'
// import FileSaver from 'file-saver'
// import XLSX from 'xlsx'

export default {
  name: 'table_category',
  directives: {
    waves
  },
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: ''
      },
      form: {
        code: '',
        name: '',
        createTime: '',
        updateTime: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      tableKey: 0
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created() {
    this.getList()
    this.sys_category_add = this.permissions['sys_category_add']
    this.sys_category_upd = this.permissions['sys_category_upd']
    this.sys_category_del = this.permissions['sys_category_del']
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.orderByField = '`r`.create_time'
      this.listQuery.isAsc = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      getObj(row.id).then(response => {
        this.form = response.data
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
      })
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    deletes(row) {
      this.$confirm(
        '此操作将永久删除该厂家信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(row.id)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    resetTemp() {
      this.form = {
        id: undefined,
        code: undefined,
        name: undefined,
        createTime: undefined,
        updateTime: undefined
      }
    },
    // exportExcel() {
    //   this.pagesize = this.total // 表格长度变长
    //   // console.info(this.pagesize)
    //   this.currentPage = 1
    //   this.$nextTick(function() {
    //     var wb = XLSX.utils.table_to_book(document.querySelector('#mainte'))
    //     var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'buffer' })
    //     try {
    //       FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '类别.xlsx')
    //     } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
    //     this.pagesize = 20
    //     return wbout
    //   })
    // },
    handleDownload() {
      const lq = this.listQuery
      lq.limit = this.total
      fetchList(lq).then(response => {
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['编码', '名称', '创建时间', '修改时间']
          const filterVal = ['code', 'name', 'createTime', 'updateTime']
          const list = response.data.records
          this.listLoading = false
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '类别信息')
        })
        this.listQuery.limit = 20
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>
